package enterpriseCustomer

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"insighttracking/apps/admin/auth"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type DeleteEnterpriseCustomerByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewDeleteEnterpriseCustomerByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *DeleteEnterpriseCustomerByIdApiLogic {
	hostname, _ := os.Hostname()
	return &DeleteEnterpriseCustomerByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *DeleteEnterpriseCustomerByIdApiLogic) DeleteEnterpriseCustomerByIdApi(req *types.IdReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	customerEntity, err := service.EnterpriseCustomerService.GetByIdApi(l.ctx, req.Id)
	if err != nil {
		return "", errors.New("传递的主键id错误")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	// 删除门店数据
	if err = service.EnterpriseCustomerService.DeleteByIdApi(l.ctx, tx, accountInfo.EnterpriseId, req.Id); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("删除失败")
	}
	// 下面全部员工账号也删除
	accountEntity, err := service.AccountService.GetByCustomerIdApi(l.ctx, accountInfo.EnterpriseId, customerEntity.ID)
	if err == nil && len(accountEntity) > 0 {
		for _, item := range accountEntity {
			// 删除登录账号信息
			if err = service.AccountService.DeleteByIdApi(l.ctx, tx, item.AccountID); err != nil {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("删除失败")
			}
			// 删除
			if err = service.EnterprisePersonService.DeleteByIdApi(l.ctx, tx, item.PersonID); err != nil {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", err
			}
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("删除失败")
	}
	return "删除成功", nil
}
